<template>
  <div class="item_search">
    <form action="/search" @submit="disabledSubmit">
      <van-search placeholder="请输入商品名称" v-model="keyword" @search="enterSearch" autofocus />
    </form>
    <div class="item_search_content">
      <div class="item_search_text clearfix">
        <div class="float-l">历史搜索</div>
        <div class="float-r" @click="clearHistory">
          <van-icon name="lajitong" style="font-size: 12px;margin-right: 3px" />清空历史记录
        </div>
      </div>
      <div class="item_search_history">
        <!-- 历史记录 -->
        <van-tag plain v-for="(his, i) in wordHistory" :key="i" @click="clickSearch(his)">{{his}}</van-tag>
      </div>
    </div>

    <van-list v-model="loading" :finished="finished" :immediate-check="false" @load="loadMore">
      <van-card
        v-for="(item, i) in list"
        :key="i"
        :desc="item.brief"
        :title="item.name"
        :thumb="item.picUrl"
        :price="item.retailPrice"
        :origin-price="item.counterPrice"
        @click="itemClick(item.id)"
      />
    </van-list>

    <is-empty v-if="isEmpty">抱歉,没有找到符合条件商品</is-empty>
  </div>
</template>

<script>
import { Card, Search, Tag, List, Icon, Dialog } from "vant";
import { goodsList } from "@/api/api";
import IsEmpty from "@/components/is-empty/";
import "@/assets/scss/iconfont/iconfont.css";
import "@/assets/scss/common.scss";
import Vue from "vue";
Vue.use(IsEmpty);
const LOCAL_STOREAGE_KEY = "search_history";
export default {
  data() {
    return {
      keyword: null,
      focusStatus: true,
      wordHistory: [],
      list: [],
      pagination: {
        page: 1,
        limit: 10
      },
      pages: 0,
      loading: false,
      finished: false,
      isEmpty: false
    };
  },
  created() {
    // 读取搜索记录
    var history = window.localStorage.getItem(LOCAL_STOREAGE_KEY);
    if (history) {
      this.wordHistory = history.split("|");
    }
  },
  methods: {
    enterSearch() {
      // 保存搜索记录
      this.addSearchHistory();
      if (this.wordHistory.indexOf(this.keyword) < 0) {
        this.wordHistory.push(this.keyword);
      }
       // 标记是否执行过搜索
      this.hasSearched = true;
      // 清除状态
      this.list = [];
      this.pagination.page = 1;
      this.pagination.limit = 10;
      this.finished = false;
      this.loadPage();
    },
    loadMore() {
      console.log("触底了");
      this.pagination.page += 1;
      this.loading = false;
      // 重置loading事件，否则不会触发触底加载事件
      this.loadPage();
    },
    addSearchHistory() {
      // 取出原来的搜索记录
      var history = window.localStorage.getItem(LOCAL_STOREAGE_KEY);
      // 将新的关键字放到原来的搜索记录列表，如果已有关键字，不再进行存储。
      if (!history || history.indexOf(this.keyword) < 0) {
        // 将新的列表放入localstorage
        if (!history) {
          window.localStorage.setItem(LOCAL_STOREAGE_KEY, this.keyword);
        } else {
          history = history + "|" + this.keyword;
          window.localStorage.setItem(LOCAL_STOREAGE_KEY, history);
        }
      }
    },
    loadPage() {
      goodsList({
        keyword: this.keyword,
        page: this.pagination.page,
        limit: this.pagination.limit
      }).then(res => {
        console.log(res.data);
        // this.list = res.data.data.list;
        var pageData = res.data.data;
        var isLast = pageData.total <= pageData.page * pageData.limit;
        if (isLast) {
          this.finished = true;
        }
        this.list.push(...pageData.list);
      });
    },
    pushHistoryTolocal(keyword) {
      const wordHistory = this.wordHistory;
      const historyKeyWord = this.getKeyWordHistory();
      if (!!keyword.trim() && historyKeyWord.indexOf(keyword) < 0) {
        wordHistory.push(keyword);
        window.localStorage.setItem("keyword", wordHistory.join("|"));
      }
    },
    getKeyWordHistory() {
      const listWord = window.localStorage.getItem("keyword");
      return listWord ? listWord.split("|") : [];
    },
    clearHistory() {
      Dialog.confirm({
        message: "确认清除历史记录"
      })
        .then(() => {
          // on confirm
          window.localStorage.removeItem(LOCAL_STOREAGE_KEY);
          this.wordHistory = [];
        })
        .catch(() => {
          // on cancel
        });
    },
    disabledSubmit() {
      return false;
    },
    itemClick(id) {
      // 此方法负责跳到商品详情页面
      // 编程式跳转，并且把当前商品的id带过去
      this.$router.push({
        name:'detail',
        params:{
          id:id
        }
      })
    },
  activated() {
    this.wordHistory = this.getKeyWordHistory();
  },
  components: {
    [Search.name]: Search,
    [Card.name]: Card,
    [Tag.name]: Tag,
    [List.name]: List,
    [Icon.name]: Icon,
    [Dialog.name]: Dialog
  }
}
}
</script>
<style lang="scss" scoped>
@import "~@/assets/scss/_var.scss";
.item_search {
  background-color: #fff;
}
.item_search_content {
  padding: 15px 10px 0;
}
.item_search_text {
  font-size: $font-size-small;
  color: $font-color-gray;
  margin-bottom: 20px;
}

.item_search_history > span {
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
